﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JSIF_WCFServer.Misc;
using JSIF_WCFServer.Misc.Logging;

namespace JSIF_WCFServer.UI
{
    public partial class DebugConsoleControl : UserControl, IMultiPurposeLogger
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public DebugConsoleControl()
        {
            InitializeComponent();
            GenericLogger.AddLoggerTarget(new LogAdapter(this));
        }

        private delegate void logConsumer(String loggerName, ILogLevels level, Exception cause, String msg);
        /// <summary>
        /// Logs a message
        /// </summary>
        /// <param name="loggerName">The name of the logger that sent the message</param>
        /// <param name="level">The severity level of the message</param>
        /// <param name="cause">The (optional) cause of the message</param>
        /// <param name="msg">The message to be logged</param>
        public void Log(String loggerName, ILogLevels level, Exception cause, String msg)
        {
            try
            {
                sb.Append(DateTime.Now);
                sb.Append(" ");
                sb.Append(level);
                sb.Append(": ");
                sb.Append(loggerName);
                sb.Append(" ");
                sb.AppendLine(msg);
                if (cause != null)
                {
                    sb.AppendLine(cause.ToString());
                }
                if (sb.Length > 1024 * 20)
                {
                    sb.Remove(0, sb.Length - 1024 * 20);
                }
                richTextBoxOutput.Text = sb.ToString();
            }
            catch { }
        }
        private StringBuilder sb = new StringBuilder();

        private class LogAdapter : IMultiPurposeLogger
        {
            public LogAdapter(DebugConsoleControl control)
            {
                _control = control;
                _logFunction = control.Log;
            }
            private DebugConsoleControl _control;
            private logConsumer _logFunction;

            public void Log(string loggerName, ILogLevels level, Exception cause, string msg)
            {
                _control.Invoke(_logFunction, loggerName, level, cause, msg);
            }
        }
    }
}
